package com.chaofan.emos.wx.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chaofan.emos.wx.db.mapper.UserMapper;
import com.chaofan.emos.wx.exception.EmosException;
import com.chaofan.emos.wx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 李超凡
 * @since 2022/3/10 22:39
 */
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session"; // 获取openid的url
        Map<String, Object> map = new HashMap<>();  // 参数
        map.put("appid", appId); // 小程序appid
        map.put("secret", appSecret); // 小程序密钥
        map.put("js_code", code); // 小程序登录时获取的code
        map.put("grant_type", "authorization_code"); // 固定值
        String result = HttpUtil.post(url, map); // 发送请求
        log.info("getOpenId result: {}", result); // 输出结果
        JSONObject jsonObject = JSONUtil.parseObj(result); // 解析结果
        String openid = jsonObject.getStr("openid"); // 获取openid
        if (StrUtil.isBlank(openid)) throw new IllegalArgumentException("临时登陆凭证错误"); // 如果openid为空，则抛出异常
        return openid;
    }

    @Override
    public int registerUser(String registerCode, String code, String nickName, String photo) {
        if ("000000".equals(registerCode)) { // 注册码正确
            if (!userMapper.haveRootUser()) { // 如果没有root用户，则创建root用户
                String openid = getOpenId(code); // 获取openid
                Map<String, Object> param = new HashMap<>();
                param.put("openId", openid); // 微信用户唯一标识
                param.put("nickName", nickName); // 昵称
                param.put("photo", photo); // 头像
                param.put("role", "[0]");
                param.put("status", "1");
                param.put("createTime", new Date());
                param.put("root", true);
                userMapper.insert(param);
                return userMapper.selectIdByOpenId(openid);
            } else {
                // 如果已经注册
                throw new EmosException("无法绑定超级管理员账号");
            }
        } else {

        }
        return 0;
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        return userMapper.searchUserPermissions(userId);
    }

    @Override
    public Integer login(String code) {
        String openid = getOpenId(code);
        Integer id = userMapper.selectIdByOpenId(openid);
        if (id == null) {
            throw new EmosException("用户不存在");
        }
        //TODO 消息队列接收消息
        return id;
    }

}
